<?php
namespace juven\libs {
    \defined('_JEXEC') or die('Restricted access');
    
    /**
     * 
     */
    class Tools {
        
        /**
         * You can use this function to send data back to the client (browser)
         * in JSON format. It only sends "raw" data, no HTML (templetes,etc.), 
         * or other elemnts. It will first set the html responce header as Content-type: application/json
         * 
         * @param array $data The data to send, in JSON format
         */
        public static function sendToClient_JSON(array $data) {
            \header('Content-Type: application/json');
            echo \json_encode($data);
        }

        /**
         * @flatten multi-dimensional array
         * @param array $array
         * @return array Returns a one-dimensional array
         */
        public static function flattenArray(array $array) {
            $ret_array = array();
            foreach (new \RecursiveIteratorIterator(new \RecursiveArrayIterator($array)) as $value){ $ret_array[] = $value; }
            return $ret_array;
        }

        /**
         * @param string $toCheck
         * @return boolean Returns TRUE if param $toCheck only contains digits [0..9], FALSE otherwise
         */
        public static function hasOnlyDigits($toCheck) {
            $digits = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
            $n = (string) $toCheck;

            $len = \strlen($n);
            if ($len<1){return \FALSE;}

            for ($i = 0; $i < $len; $i++){
                if (!\in_array(\substr($n, $i, 1), $digits)){ return \FALSE; }
            }
            return \TRUE;
        }

        /**
         * @param string $sessionID
         * @param integer $min_len
         * @param integer $max_len
         * @param boolean $throwExceptionOnError
         * @return boolean
         * @throws juvenException
         */
        public static function isValidSessionID($sessionID, $min_len=26, $max_len=128, $throwExceptionOnError=\FALSE){
            $validChars = array(
                'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
                'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
                '0','1','2','3','4','5','6','7','8','9',',','-',
            );
            $n = (string) $sessionID;

            $len = \strlen($n);

            if ($len<$min_len || $len>$max_len) {
                if ($throwExceptionOnError==\TRUE) { throw new juvenException("Invalid Session ID length"); }
                return \FALSE;
            }

            for ($i = 0; $i < $len; $i++) {
                if (!\in_array(\substr($n, $i, 1), $validChars)) { 
                    if ($throwExceptionOnError==\TRUE) { throw new juvenException("Session ID contains invalid characters"); }
                    return \FALSE;
                }
            }
            return \TRUE;
        }

        public static function PCRE_preg_last_error2string($preg_last_error){
            $msg2return = "";
            if ($preg_last_error == \PREG_NO_ERROR) {
                $msg2return = 'There is no error.';
            }
            else if ($preg_last_error == \PREG_INTERNAL_ERROR) {
                $msg2return = 'There is an internal error!';
            }
            else if ($preg_last_error == \PREG_BACKTRACK_LIMIT_ERROR) {
                $msg2return = 'Backtrack limit was exhausted!';
            }
            else if ($preg_last_error == \PREG_RECURSION_LIMIT_ERROR) {
                $msg2return = 'Recursion limit was exhausted!';
            }
            else if ($preg_last_error == \PREG_BAD_UTF8_ERROR) {
                $msg2return = 'Bad UTF8 error!';
            }
            else if ($preg_last_error == \PREG_BAD_UTF8_ERROR) {
                $msg2return = 'Bad UTF8 offset error!';
            } else {
                $msg2return = "Unknown error!";
            }
            return $msg2return;
        }
        
        public static function redirect($where){
            header('location: '.$where);
        }
        
        public static function getPrefixedTableName($tableName){ return juven::config()->db->connectionData->table_prefix.$tableName; }
        
        public static function turnResources2aTree(array $resources, $rootNodeID="0", $ID_tag="id", $parentID_tag="parent_id", $children_tag="c"){
            $tree_array2return = array();
            $references = array();
            foreach ($resources as $id => &$node) {
                $references[$node[$ID_tag]] = &$node;
                $node[$children_tag] = array();
    
                if ($node[$parentID_tag]==$rootNodeID) {
                    $tree_array2return[$node[$ID_tag]] = &$node;
                } else {
                    $references[$node[$parentID_tag]][$children_tag][$node[$ID_tag]] = &$node;
                }
            }
            return $tree_array2return;
        }
        
        public static function turnResources2aTree_v2(array $resources, $ID_tag="id", $parentID_tag="parent_id", $children_tag="c"){
            $p = array(0 => array());
            foreach($resources as $n){
              $pid = $n[$parentID_tag];
              $id = $n[$ID_tag];
              if (!isset($p[$pid])){ $p[$pid] = array("$children_tag" => array()); }
              if (isset($p[$id])){ $child = &$p[$id][$children_tag]; } else { $child = array(); }
              $p[$id] = $n;
              $p[$id][$children_tag] = &$child;
              unset($p[$id][$parentID_tag]); unset($child);

              $p[$pid][$children_tag][] = &$p[$id];    
            }
            return $p['0'][$children_tag];
        }
        
        public static function stripIllegalCharsFromUsername($username){
            $toReturn = "";
            $username_len = \strlen($username);
            for ($i = 0; $i < $username_len; $i++){
                if (\in_array(\substr($username, $i, 1), \juven\libs\juven::config()->Login->username_allowedChars)){ $toReturn .= \substr($username, $i, 1); }
            }
            return $toReturn;
        }
        
       
    }
}
?>